﻿using Microsoft.Win32;
using movie.tool.library.binding;
using movie.tool.library.ui;
using movie.tool.library.utils;
using movie.tool.module.film.model;
using movie.tool.module.film.service;
using movie.tool.module.http;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace movie.tool.module.film.ui
{
    public class ClueCardType : NotifyPropertyChanged
    {
        private string type;
        public string Type
        {
            get => type;
            set
            {
                type = value;
                SendPropertyChanged(nameof(Type));
            }
        }
        private string name;
        public string Name
        {
            get => name;
            set
            {
                name = value;
                SendPropertyChanged(nameof(Name));
            }
        }
        public ClueCardType()
        {

        }

        public ClueCardType(string type,string name)
        {
            this.Type = type;
            this.Name = name;
        }
    }
    public class SceneConfigCheckboxData : NotifyPropertyChanged
    {
        private bool check;
        public bool IsChecked
        {
            get => check;
            set
            {
                check = value;
                SendPropertyChanged(nameof(IsChecked));
            }
        }
        private SceneConfig scene;
        public SceneConfig Scene
        {
            get => scene;
            set
            {
                scene = value;
                SendPropertyChanged(nameof(Scene));
            }
        }
    }
    /// <summary>
    /// ClueInfoControl.xaml 的交互逻辑
    /// </summary>
    public partial class ClueInfoControl : BaseControl
    {
        public static readonly DependencyProperty ConfigProperty = DependencyProperty.Register("Config", typeof(MovieProject), typeof(ClueInfoControl));
        public MovieProject Config
        {
            get => (MovieProject)GetValue(ConfigProperty);
            set => SetValue(ConfigProperty, value);
        }
        public static readonly DependencyProperty BusyInfoProperty = DependencyProperty.Register("BusyInfo", typeof(BusyInfo), typeof(ClueInfoControl));
        public BusyInfo BusyInfo
        {
            get => (BusyInfo)GetValue(BusyInfoProperty);
            set => SetValue(BusyInfoProperty, value);
        }
        /// <summary>
        /// 添加、删除和保存的按钮是否可见
        /// </summary>
        public Visibility ModifyVisible
        {
            get
            {
                if (Config != null && Config.ImportProject)
                {
                    return Visibility.Collapsed;
                }
                return Visibility.Visible;
            }
        }
        private void BuildScenes()
        {
            if(Config != null && Config.Scenes != null)
            {
                if(Scenes == null)
                {
                    Scenes = new ObservableCollection<SceneConfigCheckboxData>();
                }
                Scenes.Clear();
                foreach(SceneConfig s in Config.Scenes)
                {
                    if(s == null)
                    {
                        continue;
                    }
                    SceneConfigCheckboxData item = new SceneConfigCheckboxData();
                    item.IsChecked = false;
                    item.Scene = s;
                    Scenes.Add(item);
                }
            }
        }
        private void RefreshScenesCheck()
        {
            if(Scenes != null)
            {
                if(CurrentGroup != null && CurrentGroup.Scenes != null)
                {
                    foreach (SceneConfigCheckboxData item in Scenes)
                    {
                        if (item.Scene == null)
                        {
                            continue;
                        }
                        foreach (int s in CurrentGroup.Scenes)
                        {
                            if (item.Scene.Sequence == s)
                            {
                                item.IsChecked = true;
                            }
                        }
                    }
                }
                CurrentScenes = string.Join(" ", Scenes.Where(item => item.IsChecked).Select(item => item.Scene.Name));
            }
        }
        private ObservableCollection<SceneConfigCheckboxData> scenes;
        public ObservableCollection<SceneConfigCheckboxData> Scenes
        {
            get => scenes;
            set
            {
                scenes = value;
                SendPropertyChanged(nameof(Scenes));
            }
        }
        private ClueCardGroupConfig currentGroup;
        public ClueCardGroupConfig CurrentGroup
        {
            get => currentGroup;
            set
            {
                currentGroup = value;
                BuildScenes();
                RefreshScenesCheck();
                SendPropertyChanged(nameof(CurrentGroup));
            }
        }
        private string currentScenes;
        public string CurrentScenes
        {
            get => currentScenes;
            set
            {
                currentScenes = value;
                SendPropertyChanged(nameof(CurrentScenes));
            }
        }
        private ClueCardConfig currentClueCard;
        public ClueCardConfig CurrentClueCard
        {
            get => currentClueCard;
            set
            {
                currentClueCard = value;
                SendPropertyChanged(nameof(currentClueCard));
            }
        }
        private ObservableCollection<ClueCardType> clueCardTypes;
        public ObservableCollection<ClueCardType> ClueCardTypes
        {
            get => clueCardTypes;
            set
            {
                clueCardTypes = value;
                SendPropertyChanged(nameof(ClueCardTypes));
            }
        }
        public ClueInfoControl()
        {
            InitializeComponent();
            ClueCardTypes = new ObservableCollection<ClueCardType>();
            ClueCardTypes.Add(new ClueCardType("pic", "图片线索"));
            ClueCardTypes.Add(new ClueCardType("vid", "视频线索"));
            ClueCardTypes.Add(new ClueCardType("aud", "音频线索"));
        }

        private async void AddClueGroupClick(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy)
            {
                return;
            }
            try
            {
                BusyInfo.Busy = true;
                BusyInfo.DefaultMessage();
                if (Config.ClueCardGroups == null)
                {
                    Config.ClueCardGroups = new ObservableCollection<ClueCardGroupConfig>();
                }
                ClueCardGroupConfig item = new ClueCardGroupConfig();
                item.Name = "新加分组";
                long? id = await MovieClient.SaveClueCardGroup(item, Config.Id);
                if (id is not null and > 0)
                {
                    item.Id = (long)id;
                    Config.ClueCardGroups.Add(item);
                    CurrentGroup = item;
                    MovieService.SaveProjectMovie(Config);
                }
            }
            finally
            {
                BusyInfo.Reset();
            }
        }

        private async void DeleteClueGroupClick(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy)
            {
                return;
            }
            try
            {
                BusyInfo.Busy = true;
                BusyInfo.DefaultMessage();
                if (CurrentGroup == null)
                {
                    MessageBox.Show("请选择一个分组");
                    return;
                }
                MessageBoxResult Result = MessageBox.Show("确定是否删除", "确定选项", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (Result == MessageBoxResult.Yes)
                {
                    bool result = await HttpInvoker.DeleteAsync("movieserver/clueCardGroups/" + CurrentGroup.Id);
                    if (result)
                    {
                        Config.ClueCardGroups.Remove(CurrentGroup);
                        CurrentGroup = null;
                        MovieService.SaveProjectMovie(Config);
                        MessageBox.Show("删除成功");
                    }
                }
            }
            finally
            {
                BusyInfo.Reset();
            }
        }

        private async void AddClueClick(object sender, RoutedEventArgs e)
        {
            if(CurrentGroup == null)
            {
                MessageBox.Show("请选择线索分组");
                return;
            }
            if (BusyInfo.Busy)
            {
                return;
            }
            try
            {
                BusyInfo.Busy = true;
                BusyInfo.DefaultMessage();
                ClueCardConfig item = new ClueCardConfig();
                item.Type = "pic";
                item.Name = "新加线索";
                long? id = await MovieClient.SaveClueCard(item, CurrentGroup.Id);
                if (id != null)
                {
                    item.Id = (long)id;
                    item.Group = CurrentGroup.Id;
                    if (CurrentGroup.ClueCards == null)
                    {
                        CurrentGroup.ClueCards = new ObservableCollection<ClueCardConfig>();
                    }
                    CurrentGroup.ClueCards.Add(item);
                    CurrentClueCard = item;
                }
            }
            finally
            {
                BusyInfo.Reset();
            }
        }

        private async void DeleteClueClick(object sender, RoutedEventArgs e)
        {
            if(CurrentClueCard == null)
            {
                MessageBox.Show("请选择一个线索");
                return;
            }
            if (BusyInfo.Busy)
            {
                return;
            }
            try
            {
                BusyInfo.Busy = true;
                BusyInfo.DefaultMessage();
                MessageBoxResult Result = MessageBox.Show("确定是否删除", "确定选项", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (Result == MessageBoxResult.Yes)
                {
                    bool ret = await HttpInvoker.DeleteAsync("movieserver/clueCards/" + CurrentClueCard.Id);
                    if (ret)
                    {
                        if (CurrentGroup != null)
                        {
                            CurrentGroup.ClueCards.Remove(CurrentClueCard);
                        }
                        CurrentClueCard = null;
                        MessageBox.Show("删除成功");
                    }
                }
            }
            finally
            {
                BusyInfo.Reset();
            }
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox c = sender as ComboBox;
            if (c != null)
            {
                c.SelectedItem = null;
            }
            Dispatcher.InvokeAsync(() =>
            {
                if(CurrentGroup != null)
                {
                    SendPropertyChanged(nameof(CurrentScenes));
                }
            });
            e.Handled = true;
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if(Scenes != null && CurrentGroup != null)
            {
                CurrentGroup.Scenes = Scenes.Where(item => item.IsChecked).Select(item => item.Scene.Sequence).ToArray();
                CurrentScenes = string.Join(" ", Scenes.Where(item => item.IsChecked).Select(item => item.Scene.Name));
            }
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            if (Scenes != null && CurrentGroup != null)
            {
                CurrentGroup.Scenes = Scenes.Where(item => item.IsChecked).Select(item => item.Scene.Sequence).ToArray();
                CurrentScenes = string.Join(" ", Scenes.Where(item => item.IsChecked).Select(item => item.Scene.Name));
            }
        }

        private void BaseControl_Loaded(object sender, RoutedEventArgs e)
        {
            BuildScenes();
            RefreshScenesCheck();
            SendPropertyChanged(nameof(ModifyVisible));
        }

        private async void SaveClueGroupClick(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy)
            {
                return;
            }
            try
            {
                if (CurrentGroup == null)
                {
                    MessageBox.Show("请选择一个分组");
                    return;
                }
                BusyInfo.Busy = true;
                BusyInfo.DefaultMessage();
                bool result = await MovieClient.UpdateClueCardGroup(CurrentGroup);
                if (result)
                {
                    MovieService.SaveProjectMovie(Config);
                    MessageBox.Show("更新成功");
                }
            }
            finally
            {
                BusyInfo.Reset();
            }
        }

        private void HdFileBrowser(object sender, RoutedEventArgs e)
        {
            if (CurrentClueCard == null)
            {
                MessageBox.Show("请选择一个线索再操作");
                return;
            }
            OpenFileDialog dialog = new OpenFileDialog();
            if (currentClueCard.TypePic())
            {
                //选择高清图片线索
                dialog.Filter = "图片文件(*.png,*.jpg,*.jpeg,*.bmp)|*.png;*.jpg;*.jpeg;*.bmp";
                dialog.Title = "选择高清图片线索文件";
            }
            else if (CurrentClueCard.TypeVideo())
            {
                //选择高清视频线索
                dialog.Filter = "视频文件(*.mp4)|*.mp4";
                dialog.Title = "选择高清视频线索文件";
            }else if (CurrentClueCard.TypeAudio())
            {
                //选择高清音频线索
                dialog.Filter = "音频文件(*.mp3)|*.mp3";
                dialog.Title = "选择高清音频线索文件";
            }
            
            if (CurrentClueCard != null && !string.IsNullOrEmpty(CurrentClueCard.HdFile))
            {
                string filePath = Path.Join(MovieService.ProjectJsonFilePath(Config.Id), CurrentClueCard.HdFile);
                dialog.InitialDirectory = Path.GetDirectoryName(filePath);
            }

            bool? result = dialog.ShowDialog();
            if (result != null && result == true)
            {
                string rootPath = MovieService.ProjectJsonFilePath(Config.Id);
                string path = FileUtils.Copy(dialog.FileName, rootPath, false, "clue", "hd");
                CurrentClueCard.HdFile = Path.GetRelativePath(rootPath, path);
                if ("新加线索".Equals(CurrentClueCard.Name))
                {
                    string name = Path.GetFileNameWithoutExtension(CurrentClueCard.HdFile);
                    if (!string.IsNullOrWhiteSpace(name))
                    {
                        CurrentClueCard.Name = name;
                    }
                }
            }
        }

        private void SdFileBrowser(object sender, RoutedEventArgs e)
        {
            if (CurrentClueCard == null)
            {
                MessageBox.Show("请选择一个线索再操作");
                return;
            }
            OpenFileDialog dialog = new OpenFileDialog();
            if (currentClueCard.TypePic())
            {
                //选择标清图片线索
                dialog.Filter = "图片文件(*.png,*.jpg,*.jpeg,*.bmp)|*.png;*.jpg;*.jpeg;*.bmp";
                dialog.Title = "选择标清图片线索文件";
            }
            else if (CurrentClueCard.TypeVideo())
            {
                //选择标清视频线索
                dialog.Filter = "视频文件(*.mp4)|*.mp4";
                dialog.Title = "选择标清视频线索文件";
            }
            else if (CurrentClueCard.TypeAudio())
            {
                //选择标清音频线索
                dialog.Filter = "音频文件(*.mp3)|*.mp3";
                dialog.Title = "选择标清音频线索文件";
            }

            if (!string.IsNullOrEmpty(CurrentClueCard.SdFile))
            {
                string filePath = Path.Join(MovieService.ProjectJsonFilePath(Config.Id), CurrentClueCard.SdFile);
                dialog.InitialDirectory = Path.GetDirectoryName(filePath);
            }

            bool? result = dialog.ShowDialog();
            if (result != null && result == true)
            {
                string rootPath = MovieService.ProjectJsonFilePath(Config.Id);
                string path = FileUtils.Copy(dialog.FileName, rootPath, false, "clue", "sd");
                CurrentClueCard.SdFile = Path.GetRelativePath(rootPath, path);
                if ("新加线索".Equals(CurrentClueCard.Name))
                {
                    string name = Path.GetFileNameWithoutExtension(CurrentClueCard.SdFile);
                    if (!string.IsNullOrWhiteSpace(name))
                    {
                        CurrentClueCard.Name = name;
                    }
                }
            }
        }

        private async void SaveClueCardClick(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy)
            {
                return;
            }
            try
            {
                if(CurrentClueCard == null)
                {
                    MessageBox.Show("请选择一个线索");
                    return;
                }
                BusyInfo.Busy = true;
                BusyInfo.DefaultMessage();
                bool ret = await MovieClient.UpdateClueCard(CurrentClueCard);
                if (ret)
                {
                    string rootPath = MovieService.ProjectJsonFilePath(Config.Id);
                    bool? hd = null, sd = null;  //null不用上传,true上传成功,false,上传失败
                    //查看高清文件是否修改
                    if (!string.IsNullOrEmpty(CurrentClueCard.HdFile))
                    {
                        string filePath = Path.Join(rootPath, CurrentClueCard.HdFile);
                        if (File.Exists(filePath))
                        {
                            if (!await MovieClient.ClueCardHdFileEquals(filePath, CurrentClueCard.Id))
                            {
                                //文件不一样,那上传文件
                                hd = await MovieClient.UploadClueCardHdFile(filePath, CurrentClueCard.Id, CurrentClueCard.HdFile);
                            }
                        }
                    }

                    //查看高清文件是否修改
                    if (!string.IsNullOrEmpty(CurrentClueCard.SdFile))
                    {
                        string filePath = Path.Join(rootPath, CurrentClueCard.SdFile);
                        if (File.Exists(filePath))
                        {
                            if (!await MovieClient.ClueCardSdFileEquals(filePath, CurrentClueCard.Id))
                            {
                                //文件不一样,那上传文件
                                sd = await MovieClient.UploadClueCardSdFile(filePath, CurrentClueCard.Id, CurrentClueCard.SdFile);
                            }
                        }
                    }
                    MovieService.SaveProjectMovie(Config);
                    if(hd == null && sd == null)
                    {
                        MessageBox.Show("提交成功");
                    }
                    else if(hd == null)
                    {
                        if(sd == true)
                        {
                            MessageBox.Show("提交成功");
                        }
                        else
                        {
                            MessageBox.Show("线索信息保存成功,标清文件上传失败");
                        }
                    }else if(sd == null)
                    {
                        if (hd == true)
                        {
                            MessageBox.Show("提交成功");
                        }
                        else
                        {
                            MessageBox.Show("线索信息保存成功,高清文件上传失败");
                        }
                    }
                    else
                    {
                        if(sd == true && hd == true)
                        {
                            MessageBox.Show("提交成功");
                        }else if(sd == false && hd == false)
                        {
                            MessageBox.Show("线索信息保存成功,高清标清文件都上传失败");
                        }else if(sd == false)
                        {
                            MessageBox.Show("线索信息保存成功,标清文件上传失败");
                        }
                        else
                        {
                            MessageBox.Show("线索信息保存成功,高清文件上传失败");
                        }
                    }
                }
            }
            finally
            {
                BusyInfo.Reset();
            }
        }

        private async void HdFileDownload(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy || currentClueCard == null)
            {
                return;
            }
            try
            {
                BusyInfo.Busy = true;
                BusyInfo.BusyMessage = "下载中...";
                string rootPath = MovieService.ProjectJsonFilePath(Config.Id);
                await MovieSynchronizer.syncClueCardHdFile(rootPath, currentClueCard);
            }
            finally
            {
                BusyInfo.Reset();
            }
        }

        private async void SdFileDownload(object sender, RoutedEventArgs e)
        {
            if (BusyInfo.Busy || currentClueCard == null)
            {
                return;
            }
            try
            {
                BusyInfo.Busy = true;
                BusyInfo.BusyMessage = "下载中...";
                string rootPath = MovieService.ProjectJsonFilePath(Config.Id);
                await MovieSynchronizer.syncClueCardSdFile(rootPath, currentClueCard);
            }
            finally
            {
                BusyInfo.Reset();
            }
        }
    }
}
